package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

@RequestMapping("api/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("passport/logout")
    public Result logout(@RequestHeader(value = "token",required = false)String headerToken,
                         @CookieValue(value = "token",required = false) String cookieToken){
        String token = headerToken;
        if (StringUtils.isEmpty(token)){
            token = cookieToken;
        }
        userService.logout(token);

        return Result.ok();
    }

    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo info, HttpServletRequest request){
        UserInfo userInfo = userService.login(info);

        /**
         * 1、给Result里面返回这个数据
         * {
         *     code:xxxx
         *     message:"",
         *     data:{
         *         token   唯一令牌
         *         nickName    昵称
         *     }
         * }
         *
         *2、用户登录成功，给redis存用户信息
         *  user:info:你的token（有过期时间）
         *  存的值：{"userId":1,"ipAddr":"xxx"}
         *
         */
        if (userInfo == null){
            Result.build(null,ResultCodeEnum.PASSWD_ERROR);
        }

        Map<String,Object> success = userService.handleLoginSuccess(userInfo,request);

        return Result.ok(success);
    }

    @PostMapping("/address/list")
    public List<UserAddress> getCurrentUserAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userService.getUserAddressListByUserId(userId);
        return userAddressList;
    }
}
